import type { DocumentFetchConfig, DocumentFetchResult } from '../index'
import { logger } from '../../../types/constants'
import { DocumentFetchMethod, DocumentOperator } from '../index'

/**
 * 图片信息
 */
export interface ImageInfo {
  size: string
  bulk: string
  resolution?: string
  format?: string
  [key: string]: string | undefined
}

/**
 * 图片信息提取配置
 */
export interface ImageInfoExtractorConfig {
  selectors: {
    size: string
    bulk: string
    [key: string]: string
  }
  fetchConfig?: Partial<DocumentFetchConfig>
}

/**
 * 图片信息提取结果
 */
export interface ImageInfoExtractResult {
  success: boolean
  data?: ImageInfo
  error?: Error
  methodUsed?: string
  duration?: number
  retryCount?: number
  statusCode?: number
}

/**
 * 图片信息提取器
 */
export class ImageInfoExtractor {
  private readonly name: string = 'ImageInfoExtractor'
  private readonly documentOperator: DocumentOperator = DocumentOperator.getInstance()

  /**
   * 从详情页提取图片信息
   */
  public async extractFromDetailPage(
    detailUrl: string,
    config: ImageInfoExtractorConfig,
  ): Promise<ImageInfoExtractResult> {
    const startTime = Date.now()
    const fetchConfig: DocumentFetchConfig = {
      url: detailUrl,
      method: DocumentFetchMethod.FETCH,
      ...config.fetchConfig,
    }

    const docResult: DocumentFetchResult<Document> = await this.documentOperator.fetchDocument(fetchConfig)
    const doc = docResult.data || document
    const result = this.extractInfo($(doc), config.selectors, detailUrl)

    logger.debug(`[${this.name}] 图片信息提取成功`, {
      url: detailUrl,
      methodUsed: 'fetch',
      duration: Date.now() - startTime,
    })

    return {
      success: true,
      data: result,
      methodUsed: 'fetch',
      duration: Date.now() - startTime,
    }
  }

  /**
   * 提取信息的具体实现
   */
  private extractInfo(
    $doc: JQuery<Document>,
    selectors: ImageInfoExtractorConfig['selectors'],
    url: string,
  ): ImageInfo {
    const info: ImageInfo = {
      size: '',
      bulk: '',
    }

    // 提取所有配置的选择器信息
    for (const [key, selector] of Object.entries(selectors)) {
      if (selector) {
        const value = $doc.find(selector).text().trim()
        if (value) {
          info[key] = value
        }
      }
    }

    // 验证必要信息
    if (!info.size && !info.bulk)
      logger.warn(`[${this.name}] 未找到图片尺寸和体积信息：${url}`)

    return info
  }
}
